<template>
	<view class="page">
		<!-- 下拉刷新组件 -->
		<mix-pulldown-refresh id="mix-pulldown-refresh" ref="mixPulldownRefresh" style="position: relative;"
			:top="mixPulldownRefreshTop" @refresh="onPulldownReresh" @setEnableScroll="setEnableScroll">
			<scroll-view id="scroll-view" class="panel-scroll-box" scroll-y="true" @scroll="scroll"
				:scroll-into-view="'siv-'+ scrollIntoView" @tap="hideModal">
				<view class="chat">
					<view class="chat-prompt">{{ loadParams[allHistoryLoaded]}}</view>

					<block v-for="(item, index) in messages" :key="index">
						<view class="item" :class="{'self' : item.senderId == (currentUser && currentUser.uuid)}">
							<view v-if="item.senderId != (currentUser && currentUser.uuid)" class="avatar radius"
								:style="{ backgroundImage: 'url('+ friend.avatar + ')' }"
								@tap="userDetailPage(friend.uuid)"></view>
							<view v-else class="avatar radius"
								:style="{ backgroundImage: 'url('+ currentUser.avatar + ')' }"
								@tap="userDetailPage(currentUser.uuid)"></view>

							<view class="main">
								<!-- 语音消息 -->
								<audio-player v-if="item.type=='audio'" :src="item.payload.url"
									:duration="item.payload.duration"
									:customClass="{'self':item.senderId==(currentUser && currentUser.uuid)}">
								</audio-player>
								<!-- 图片消息 -->
								<image-wrap v-else-if="item.type=='image'" :src="item.payload.url"></image-wrap>
								<!-- 视频消息 -->
								<video-wrap v-else-if="item.type=='video'" :videoSrc="item.payload.url"
									:imgSrc="item.payload.imgUrl" :vWidth="item.payload.width"
									:vHeight="item.payload.height" :duration="item.payload.duration">
								</video-wrap>
								<!-- 文件类型 -->
								<file-wrap v-else-if="item.type=='file'" :title="item.payload.name"
									:extension="item.payload.extension" :size="item.payload.size"
									:unit="item.payload.unit"></file-wrap>
								<!-- 语音电话 -->
								<call-wrap v-else-if="item.type=='tel'" :mode="item.payload.mode"
									:duration="item.payload.duration" :status="item.payload.status">
								</call-wrap>
								<!-- 视频电话 -->
								<call-wrap v-else-if="item.type=='mov'" :mode="item.payload.mode"
									:duration="item.payload.duration" :status="item.payload.status">
								</call-wrap>
								<!-- 普通消息 -->
								<default-wrap v-else-if="item.type == 'text'" :content="item.payload.content">
								</default-wrap>
							</view>
						</view>

						<view :id="'siv-'+ index"></view>
					</block>
				</view>
			</scroll-view>
		</mix-pulldown-refresh>

		<!-- 输入框 -->
		<input-bottom id="bottom"></input-bottom>
	</view>
</template>

<script>
	import dataList from '@/static/json.js';
	import audioPlayer from './components/audio-player/audio-player.vue'
	import imageWrap from './components/image-wrap/image-wrap.vue'
	import videoWrap from './components/video-wrap/video-wrap.vue'
	import fileWrap from './components/file-wrap/file-wrap.vue'
	import callWrap from './components/call-wrap/call-wrap.vue'
	import defaultWrap from './components/default-wrap/default-wrap'
	import inputBottom from './components/input-bottom/input-bottom'
	import {
		bus
	} from '../../../main.js'

	export default {
		components: {
			audioPlayer,
			imageWrap,
			videoWrap,
			fileWrap,
			callWrap,
			defaultWrap,
			inputBottom
		},
		data() {
			return {
				bottom: 0,
				modalName: '',
				friend: {},
				currentUser: {},
				//已经接收到的消息
				messages: [],
				//已经加载完所有历史消息
				allHistoryLoaded: 0, // 0下拉获取历史消息，1获取中，2已经没有更多的历史消息
				loadParams: {
					0: '下拉获取历史消息',
					1: '获取中',
					2: '已经没有更多的历史消息',
				},
				enableScroll: true,
				video: {
					visible: false,
					url: '',
				},
				scrollIntoView: '',

				inputBottom: 0,
			};
		},
		computed: {
			mixPulldownRefreshTop() {
				return this.bottom + this.inputBottom;
			},
		},
		watch: {
			mixPulldownRefreshTop(newVel, oldVal) {
				this.scrollToBottom()
			},
		},
		async onLoad(options) {
			this.messages = dataList.messages
			this.friend = dataList.friendInfo
			this.currentUser = dataList.currentUserInfo

			uni.setNavigationBarTitle({
				title: this.friend.name
			});

			//监听新消息，收到新消息，是滚动到最底部
			bus.$on('updateContent', val => {
				let item = {
					senderId: this.currentUser.uuid,
					...val
				}
				this.messages.push(item)
				console.log(this.messages);
				this.scrollToBottom()
			})

			// 底部输入框的高度 
			bus.$on('updateBottomH', val => {
				this.bottom = val
			})

			// 监听页面跳转 
			bus.$on('updateNavigate', val => {
				this.goToPage(val)
			})

			this.$nextTick(function() {
				setTimeout(() => {
					this.scrollToBottom()
				}, 100)
			})
		},
		onUnload() {
			bus.$off('updateContent')
			bus.$off('updateBottomH')
		},
		methods: {
			hideModal() {
				bus.$emit('updateInputStatus', 'promptHide')
			},
			//像微信那样显示时间，如果有几分钟没发消息了，才显示时间
			//todo:本不需要该方法，可以在标签里完成，但小程序有兼容性问题，被迫这样实现
			renderMessageDate(message, index) {
				// if (index === 0) {
				// 	return this.$formatTimestamp(message.timestamp);
				// } else {
				// 	if (message.timestamp - this.messages[index - 1].timestamp > 2 * 60 * 1000) {
				// 		return this.$formatTimestamp(message.timestamp);
				// 	}
				// }
				// return '';
			},
			loadMoreHistoryMessage() {
				//历史消息
				let lastMessageTimeStamp = Date.now();
				let lastMessage = this.messages[0];
				if (lastMessage) {
					lastMessageTimeStamp = lastMessage.timestamp;
				}
				let currentLength = this.messages.length;

				setTimeout(() => {
					this.allHistoryLoaded = 2;
					this.$refs.mixPulldownRefresh && this.$refs.mixPulldownRefresh.endPulldownRefresh();
				}, 500);
			},
			//下拉刷新
			onPulldownReresh() {
				this.allHistoryLoaded = 1;
				setTimeout(() => {
					this.loadMoreHistoryMessage();
				}, 500);
			},
			goToPage(url) {
				uni.navigateTo({
					url: url
				})
			},
			//接听电话
			raiseTel(id) {},
			//接听视频
			raiseMovie(id) {},
			//监听滚动
			scroll(e) {
				this.scrollIntoView = null;
			},
			// 滚动到底部
			scrollToBottom() {
				this.scrollIntoView = null;
				this.$nextTick(function() {
					this.scrollIntoView = this.messages.length - 1
				});
			},
			markPrivateMessageAsRead(friendId) {},
			//在线预览文件
			downLoadFile(file) {
				console.log('在线预览文件', file);
			},
			//跳转用户朋友圈
			userDetailPage(uuid) {
				console.log('跳转用户朋友圈', uuid);
			},
			//设置scroll-view是否允许滚动，在小程序里下拉刷新时避免列表可以滑动
			setEnableScroll(enable) {
				if (this.enableScroll !== enable) {
					this.enableScroll = enable
				}
			},
		}
	};
</script>

<style lang="scss">
	.page {
		position: absolute;
		width: 100%;
		height: 100%;
		background-color: #F8F8F8;

		.chat {
			display: flex;
			flex-direction: column;

			.item {
				padding: 0 10px 12px;

				display: flex;
				justify-content: flex-start;
				align-items: center;

				.avatar {
					position: relative;
					width: 40px;
					height: 40px;
					margin: 0;
					padding: 0;
					// background-color: #ccc;
					color: #ffffff;
					text-align: center;
					white-space: nowrap;
					background-size: cover;
					background-position: center;
					vertical-align: middle;
					font-size: 1.5em;
					font-variant: small-caps;

					display: flex;
					justify-content: center;
					align-items: center;
				}

				.main {
					max-width: calc(100% - 104px);
					margin: 0 10px;
				}
			}
		}
	}

	.panel-scroll-box {
		height: 100%;
	}

	.self {
		flex-direction: row-reverse;
		justify-content: flex-start;
	}

	uni-image {
		max-width: 600rpx;
		max-height: 240rpx;
		display: inline-block;
		overflow: hidden;
		position: relative;
	}

	.self .box::after {
		content: "";
		right: -6px;
		left: auto;
	}

	.chat-prompt {
		padding: 12px;
		text-align: center;
		font-size: 12px;
		color: #b5b5b5;
	}
</style>
